<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>刮一刮</title>
</head>

<style>
    * {
        margin: 0;
        padding: 0;
    }

    body {
        background-color: #333;
    }

    #wapper {
        width: 150px;
        height: 50px;
        position: relative;
        background-color: red;
    }

    .wapper-inner {
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        width: 100%;
        height: 100%;
        font-size: 14px;
        text-indent: 77px;
        line-height: 50px;
        font-weight: bold;
        position: absolute;
        left: 0;
        top: 0;
    }

    #card {
        position: absolute;
        left: 0;
        top: 0;
    }
</style>

<body>
    <div id="wapper">
        <div class="wapper-inner"></div>
        <canvas id="card" width="150" height="50"></canvas>
    </div>

    <button id="clear">再刮一次</button>
</body>

<script>
    /** @type {HTMLCanvasElement} */
    let wapper = document.querySelector('#wapper')
    let wapperInner = document.querySelector('.wapper-inner')

    createCardCanvas(wapper, wapperInner)


    let clear  = document.querySelector('#clear')
    clear.onclick = function () {
        console.log('123')
        wapper.removeChild(wapper.lastElementChild)
        createCardCanvas(wapper, wapperInner)
    }

    function createCardCanvas(node, wapperInner) {
        let can = document.createElement("canvas")
        let ctx = can.getContext("2d")
        can.id = "card"
        can.width = "150"
        can.height = "150"

        //绘制封面图
        let img = new Image();
        img.src = "./img/1.png"
        img.onload = () => {
            ctx.drawImage(img, 0, 0, 150, 50) //x y 宽 高
        }
        let arrData = ["谢谢惠顾", "奖品1", "奖品2", "奖品3", "奖品4"]
        let random = Math.trunc(Math.random() * 4)
        wapperInner.innerHTML = arrData[0]
        //对应的鼠标事件
        let isBegin = false //是否开始刮一刮
        can.onmousedown = () => { //开始
            isBegin = true
        }

        can.onmousemove = (e) => { //刮 (移动)
            let event = e || window.event //获取事件对象
            if (isBegin) {
                let x = e.clientX - wapper.offsetLeft;
                let y = e.clientY - wapper.offsetTop;
                ctx.fillStyle = "#eeeeee"
                ctx.globalCompositeOperation = "destination-out"
                ctx.arc(x, y, 5, 0, Math.PI * 2);
                ctx.fill()
            }
        }

        can.onmouseup = () => { //结束
            isBegin = false
        }

        node.appendChild(can)
    }
</script>

</html>